<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Released under the MIT License.
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------

namespace app\home\controller;

use cmf\controller\HomeBaseController;
use think\cache\driver\Redis;
use think\log;
//use think\Response;
class LoginController extends HomeBaseController
{
	protected $app_id = 'wx2759a229ef410aef';
	protected $appsecret = '648923a26624549c1fae6e0445bd2436';


	/**
	*
	*
	**/
	/*public function testWx()
	{
		$appid = $this->app_id;
        $appsecret =$this->appsecret;
		$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$appsecret;
		$data = file_get_contents($url);
		var_dump($data);
	}*/




	/**
	*
	*授权登录-登录请求
	**/
	public function wxLogin()
	{
        WL(['msg' => '登录go'], 'sudu');
        $url = $this->request->url(true);
        $redis = new Redis();
       
		//接收code
		$code = $this->request->param('code', '');
		if(empty($code))
		{
			$appid = $this->app_id;
        	$appsecret =$this->appsecret;
			$request = request();
            $callback = $request->url($url);//微信服务器回调url，这里是本页url
            $redirect_uri=urlencode($callback);
            $url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri='.$redirect_uri.'&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect';
            header("location:$url");
            return;
		}

		//获取用户OPEN——ID
		$data = $this->get_access_token($code);//获取网页授权access_token和用户openid
		if(!empty($data['errcode']))
		{
		  $this->error($data['errmsg']);
		}

        //通过open_id,判断用户是否已存在
        $memModel = new \app\home\model\MemberModel();
        $info = $memModel->getMemberIdWhereOpenId($data['openid'], 'member_id, status');

        //获取用户微信资料
        $wx_info = $this->getMemberInfo($data['access_token'], $data['openid']);

        //查找用户唯一unionid，匹配用户
        if(empty($info))
        {
            $info = $memModel->getMemberIdWhereUnionid($wx_info['unionid'], 'member_id, status');
        }

        $get_real_ip = $_SERVER['REMOTE_ADDR'];
        WL(['msg' => '用户ip', 'ip' => $get_real_ip], 'login');
        
        $login_time = date('Y-m-d H:i:s');
        if(empty($info))
        {
        	//无，注册一条信息
            $data = [
                'open_id' => $data['openid'], 
                'login_time' => $login_time, 
                'login_ip' => $get_real_ip,
                'invite' => $this->cmf_random_string(),
                'unionid' => $wx_info['unionid'],
                'logo' => $wx_info['headimgurl'],
                'nickname' => $this->filterEmoji($wx_info['nickname']),
                'sex' => ($wx_info['sex'] == 1) ? '男' : '女',
            ];

        	$member_id = $memModel->addMemberInfo($data);
        	if(empty($member_id))
        	{
        		$this->error('添加用户信息失败，系统错误');
        	}
        }else{
        	//判断用户状态
        	if($info['status'] != 1)
        	{
        		$this->error('该账号已被禁用，请联系管理员');
        	}
        	//存在，更新登录时间和IP
        	$member_id = $info['member_id'];
            $update = [
                'open_id' => $data['openid'],
                'login_time' => $login_time, 
                'login_ip' => $get_real_ip,
                'logo' => $wx_info['headimgurl'],
                'nickname' => $this->filterEmoji($wx_info['nickname']),
                'sex' => ($wx_info['sex'] == 1) ? '男' : '女',
                ];
        	$res = $memModel->updateMemberInfo($info['member_id'], $update);


            //清理access_token缓存，用户发通知消息
            $notice_str = 'access_token_member_uid'.$member_id;
            $redis->set($notice_str, '');
        }

        //缓存session,跳转到首页
        session('user_id', $member_id);
        $login_url = session('login_url');

        WL(['msg' => '登录end'], 'sudu');
        if(!empty($login_url))
        {
            return $this->redirect($login_url);
        }else{
            //判断是否刚注册
            if(empty($info))
            {
                return $this->redirect('/?one_login=1');
            }else{
                return $this->redirect('/');
            }
            
        }
        
	}


	 /**
     * 3、使用code换取access_token
     * @param string 用于换取access_token的code，微信提供
     * @return array access_token和用户openid数组
     */
    private function get_access_token($code){
        $appid = $this->app_id;
        $appsecret =$this->appsecret;

        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $appsecret . '&code=' . $code . '&grant_type=authorization_code';

        $user = json_decode(file_get_contents($url));
        $data = json_decode(json_encode($user),true);//返回的json数组转换成array数组
        return $data;
    }



    /**
    *
    *拉取用户资料
    **/
    public function getMemberInfo($access_token, $open_id)
    {
        $url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$open_id.'&lang=zh_CN';
        $user = json_decode(file_get_contents($url));
        $data = json_decode(json_encode($user),true);//返回的json数组转换成array数组
        return $data;
    }


    /**
    *
    *获取用户IP
    *
    **/
    public function getMemberIpSite($access_token)
    {
        $url = "https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=".$access_token;
        $user = json_decode(file_get_contents($url));
        $data = json_decode(json_encode($user),true);//返回的json数组转换成array数组
        return $data;
    }



    public function cmf_random_string($len = 6)
    {
        $chars    = [
            "A", "B", "C", "D", "E", "F", "G","H", "J", "K", "L", "M", "N", "P", "Q", "R","S", "T", "U", "V", "W", "X", "Y", "Z"
        ];
        $charsLen = count($chars) - 1;
        shuffle($chars);    // 将数组打乱
        $output = "";
        for ($i = 0; $i < $len; $i++) {
            $output .= $chars[mt_rand(0, $charsLen)];
        }
        //是否已存在，存在就回调再随机
        $memModel = new \app\home\model\MemberModel();
        $where = [
            ['invite', '=', $output]
        ];
        $info = $memModel->geetMemberWhereReturnInfo($where, 'member_id');
        if(!empty($info))
        {
            $output = $this->cmf_random_string();
        }
        return $output;
    }



    public function filterEmoji($str = ''){
        $str = json_encode($str);
        $str = json_decode(preg_replace("#(\\\ud[0-9a-f]{3})#i", "", $str));
        return $str;
    }


}